package com.unitechs.commons.utils;

import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

//TODO 开发中
public final class ZyucFileUtil {
    private ZyucFileUtil() {
        //防止实例化
        throw new AssertionError();
    }

    public static File exportExcelToFile(SXSSFWorkbook workbook, String excelName) throws IOException {
        File excelFile = File.createTempFile(excelName, ".xlsx");
        try (FileOutputStream fileOut = new FileOutputStream(excelFile)) {
            workbook.write(fileOut);
        }
        return excelFile;
    }

    public static void convertWorkbookToPdfResponse(Workbook workbook, HttpServletResponse response) throws IOException {
        try (OutputStream out = response.getOutputStream();
             ZyucAutoCloseableDocument document = new ZyucAutoCloseableDocument(out)) {

            // 设置响应头，指定内容类型为 PDF
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=converted_document.pdf");

            // 逐个页面将 Excel 内容写入 PDF
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                document.getDocument().newPage();

                // 添加 Excel 内容到 PDF
                addSheetContentToPdf(workbook.getSheetAt(i), document);

                // 在这里添加其他内容，例如表格、图片等
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addSheetContentToPdf(Sheet sheet, ZyucAutoCloseableDocument document) {
        try {
            PdfPTable table = new PdfPTable(sheet.getRow(0).getPhysicalNumberOfCells());

            for (Row row : sheet) {
                for (Cell cell : row) {
                    PdfPCell pdfCell = new PdfPCell(new Phrase(cell.toString()));
                    table.addCell(pdfCell);
                }
            }

            document.getDocument().add(table);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
